package cn.me.alphamq.common.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 反射工具
 *
 * @author f
 */
public class ReflectUtil {

    /**
     * 判断一个对象的类的全路径是否包含指定字符串
     *
     * @param o   待判断的对象
     * @param tar 指定字符串
     * @return
     */
    public static boolean containsInPath(Object o, String tar) {
        return o.getClass().getName().contains(tar);
    }

    /**
     * 从接口中获取指定的泛型
     *
     * @param o     接口的 Class 对象
     * @param index 泛型的索引
     * @return
     */
    public static Class<?> getGenericFromInterface(Object o, int index) {
        Type[] types = o.getClass().getGenericInterfaces();
        ParameterizedType parameterizedType = (ParameterizedType) types[index];
        Type type = parameterizedType.getActualTypeArguments()[index];
        return checkType(type, index);
    }

    // 检查类型是否合法
    private static Class<?> checkType(Type type, int index) {
        if (type instanceof Class<?>) {
            return (Class<?>) type;
        } else if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;
            Type t = pt.getActualTypeArguments()[index];
            return checkType(t, index);
        } else {
            String className = type == null ? "null" : type.getClass().getName();
            throw new IllegalArgumentException("Expected a Class, ParameterizedType" +
                    ", but <" + type + "> is of type " + className);
        }
    }

}
